//    Copyright (C) Kherty.  All rights reserved.
using OpenLS.Core.Serialization;
using OpenLS.Vml;
using OpenLS.Vml.Serialization;

namespace OpenLS.Spreadsheet
{
    class LegacyDrawingHelper: IOfficeXmlSerializableAs
    {
        public static VmlDrawing ReadOptionalVmlElementAs(ReadContext rc, string name)
        {
            var legacyDrawing = rc.ReadOptionalElementAs<LegacyDrawingHelper>(name);
            if (legacyDrawing != null)
                return legacyDrawing.VmlDrawing;
            return null;
        }
        public static void WriteOptionalVmlElementAs(VmlDrawing vmlDrawing, WriteContext rc, string name)
        {
            if (vmlDrawing == null)
                return;
            var legacyDrawing = new LegacyDrawingHelper() {VmlDrawing = vmlDrawing};
            rc.WriteElementAs(legacyDrawing, name);
        }

        public VmlDrawing VmlDrawing { get; set; }

        #region IOfficeXmlSerializable Members

        void IOfficeXmlSerializableAs.ReadXmlAs(string name, ReadContext context)
        {
            using (ReadContext c = context.Read(name))
            {
                //string id = c.GetString(OfficeConstants.RelationshipNamespace + "id");
                this.VmlDrawing = new VmlDrawing();
                //PackageRelationship relationship = c.Part.GetRelationship(id);
               // PackagePart newPart = c.Part.Package.GetPart(PackUriHelper.ResolvePartUri(relationship.SourceUri, relationship.TargetUri));
                this.VmlDrawing.ReadFromParentXml(c);

                /*Stream stream = newPart.GetStream();
                XmlReader reader = new XmlTextReader(stream);
                RelatedReadContext result = new RelatedReadContext(reader, newPart, "", stream, relationship);
                result.CopyDataFrom(c);
                var cc = (ReadContext) result;
              //  PackageRelationship r = c.Part.GetRelationship(id);
                using (ReadContext c2 = c.OpenRelatedContext(id, ""))
                {
                    VmlDrawing = c2.ReadElement<Vml.VmlDrawing>();
                }*/
            }
        }

        void IOfficeXmlSerializableAs.WriteXmlAs(string name, WriteContext context)
        {
            using (WriteContext c = context.Write(name))
            {
                using (var c2 = c.CreateRelatedContext(null, null, c.GetAvailableUri("../drawings/drawing{0}.vml"),VmlConstants.VmlRelationshipUri,VmlConstants.VmlContentType))
                {
                    c.SetString(OfficeConstants.RelationshipNamespace + "id", c2.Relationship.Id);
                    c2.WriteElement(VmlDrawing);
                }
            }
        }
        #endregion
    }
}
